import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/ssh_connection.dart';
import '../services/database_service.dart';
import '../services/ssh_service.dart';
import 'connection_edit_screen.dart';
import 'terminal_screen.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  late Future<List<SSHConnection>> _connectionsFuture;

  @override
  void initState() {
    super.initState();
    _loadConnections();
  }

  void _loadConnections() {
    final databaseService = context.read<DatabaseService>();
    _connectionsFuture = databaseService.getConnections();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('CLSSH - SSH客户端'),
        actions: [
          IconButton(
            icon: const Icon(Icons.add, color: Colors.white),
            onPressed: () => _addConnection(),
          ),
        ],
        iconTheme: const IconThemeData(color: Colors.white), // 确保所有图标都是白色
      ),
      body: FutureBuilder<List<SSHConnection>>(
        future: _connectionsFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }

          if (snapshot.hasError) {
            return Center(child: Text('错误: ${snapshot.error}'));
          }

          final connections = snapshot.data ?? [];

          if (connections.isEmpty) {
            return const Center(
              child: Text('暂无SSH连接，点击 + 添加新连接'),
            );
          }

          return ListView.builder(
            itemCount: connections.length,
            itemBuilder: (context, index) {
              final connection = connections[index];
              return _buildConnectionCard(connection);
            },
          );
        },
      ),
    );
  }

  Widget _buildConnectionCard(SSHConnection connection) {
    return Card(
      margin: const EdgeInsets.all(8.0),
      child: ListTile(
        leading: const Icon(Icons.computer, size: 40),
        title: Text(connection.name),
        subtitle: Text('${connection.username}@${connection.host}:${connection.port}'),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(
              icon: const Icon(Icons.edit),
              onPressed: () => _editConnection(connection),
            ),
            IconButton(
              icon: const Icon(Icons.delete),
              onPressed: () => _deleteConnection(connection),
            ),
          ],
        ),
        onTap: () => _connectToServer(connection),
      ),
    );
  }

  void _addConnection() async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const ConnectionEditScreen()),
    );
    
    if (result == true) {
      setState(() {
        _loadConnections();
      });
    }
  }

  void _editConnection(SSHConnection connection) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ConnectionEditScreen(connection: connection),
      ),
    );
    
    if (result == true) {
      setState(() {
        _loadConnections();
      });
    }
  }

  void _deleteConnection(SSHConnection connection) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除连接 "${connection.name}" 吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      final databaseService = context.read<DatabaseService>();
      await databaseService.deleteConnection(connection.id);
      setState(() {
        _loadConnections();
      });
    }
  }

  void _connectToServer(SSHConnection connection) async {
    final sshService = context.read<SSHService>();
    final connected = await sshService.connect(connection);

    if (!connected) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('连接失败，请检查配置')),
        );
      }
      return;
    }

    // 更新使用统计
    final databaseService = context.read<DatabaseService>();
    await databaseService.updateConnectionUsage(connection.id);

    if (mounted) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => TerminalScreen(connection: connection),
        ),
      );
    }
  }
}